package net.sk.dc;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import net.sk.pt.State;
import net.sk.pt.StateUtil;
import net.sk.web.Provider;
import net.sk.web.StateCenter;

public class Robot implements Runnable {

	private final int loop_span = 1000;
	private boolean bStop = false;
	private Provider pr;
	final static String CN_ROBOT_DATA="ROBOT_DATA";
	private Object[] node_ids;
	private String label;
	private String[] lbs;
	
	public Robot(Provider pr,Object[] node_ids,String label){
		this.pr = pr;
		this.node_ids = node_ids;
		this.label=label;
		lbs = splitLabel(label,'{','}');
		randAll(State.ACTION_ADD);
	}
	private String[] splitLabel(String label, char pch, char tch){
		ArrayList<String> sl = new ArrayList<String>();
		StringBuffer sbuf = new StringBuffer();
		boolean start=false;
		for(int i=0; i<label.length(); i++){
			char ch = label.charAt(i);
			if(ch==pch){
				start=true;
				sbuf = new StringBuffer();				
			}else if(ch==tch){
				start=false;
				sl.add(sbuf.toString());
			}else{
				if(start){
					sbuf.append(ch);
				}
			}
		}
		String[] ss = new String[sl.size()];
		for(int i=0; i<sl.size(); i++){
			ss[i]=sl.get(i);
		}
		return ss;
	}
	private void randAll(char action){
		for(int i=0; i<node_ids.length; i++){
			pr.send(randValue((Integer)node_ids[i],action));
		}
	}
	private State randValue(int node_id,char action){
		State s = new State();
		s.setCn(CN_ROBOT_DATA);
		s.setAction(action);
		HashMap<String,Object> its = new HashMap<String,Object>();
		s.setItems(its);
		s.setKey(StateCenter.DAO_DEVICE+StateUtil.keyJoin+node_id);
		for(int i=0; i<lbs.length; i++){
			its.put(lbs[i], new Date().getTime());
		}
		//its.put("dt", new Date().getTime());
		//its.put("tmpr", getscale(Math.random()*50));
		//its.put("humi", getscale(Math.random()*20));
		return s;
	}
	private double getscale(double din){
		String s = String.format("%.2f",din);
		return Double.parseDouble(s);
	}
	public void stop(){
		bStop =  true;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(!bStop){
			try {
				Thread.sleep(loop_span);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			randAll(State.ACTION_UPDATE);
		}
		//通知删除状态
		randAll(State.ACTION_REMOVE);
	}

}
